import { baseStorage } from "@/utils/storage";
import { defineStore } from "pinia";
import { reactive, watch } from "vue";

export const AUTH_STORE = "auth";

interface ZAuthState {
  token: string | null;
  userInfo: any;
}

export const useAuthStore = defineStore(AUTH_STORE, () => {
  const cache = baseStorage.get<ZAuthState>(AUTH_STORE);
  const authState = reactive<ZAuthState>({
    token: cache?.token ?? null,
    userInfo: cache?.userInfo ?? null,
  });

  watch(authState, () => {
    baseStorage.set(AUTH_STORE, authState);
  });

  function setToken(token: string) {
    authState.token = token;
  }

  function removeToken() {
    authState.token = null;
  }

  function setUserInfo(info: any) {
    authState.userInfo = info;
  }

  function clear() {
    authState.token = null;
    authState.userInfo = null;
  }

  return {
    getToken: () => authState.token,
    getUserInfo: () => authState.userInfo,
    hasToken: () => authState.token != null,
    setToken,
    removeToken,
    setUserInfo,
    clear,
  };
});
